package owg.util.editor2d.modes;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import owg.util.editor2d.ConstructorParams;
import owg.util.editor2d.Editor2D;
import owg.util.editor2d.operations.ConstructorInvoker;
import owg.util.editor2d.operations.Destroyer;
import owg.util.editor2d.operations.Reviver;
import owg.util.editor2d.operations.Unconstructor;
import owg.util.euclidian.V2D;
import owg.util.opengl.EGL;

public class Paint extends Mode {
	public static boolean SEPARATE_UNDO = false;
	
	private static final byte PAINT_CREATE = 0b01;
	private static final byte PAINT_DESTROY = 0b10;
	
	public final byte paint;
	
	private boolean append = false;
	private V2D lastMouse = new V2D();
	private ConstructorParams cons;
	
	public Paint(Editor2D e)
	{
		super(e);
		byte pt = 0;
		cons = null;
		if(e.settings.createPaint.get())
		{
			pt |= PAINT_CREATE;
			cons = e.getSelectedConstructorParams();
		}
		if(e.settings.destroyPaint.get())
			pt |= PAINT_DESTROY;
		
		paint = pt;
	}
	
	@Override
	public void mouse(MouseEvent e) {
		V2D mpos = editor.eventHandler().getSnappedMouse();
		
		if((e.getID() == MouseEvent.MOUSE_PRESSED && e.getButton() == MouseEvent.BUTTON1) || 
			((e.isShiftDown() || editor.settings.snapEnabled.get()) && !mpos.equals(lastMouse)))
		{
			//if(editor.settings.snapEnabled.get()) TODO: Line-paint
				
			if((paint&PAINT_DESTROY) != 0 && editor.getHighlightedObject() != null)
			{
				Destroyer destroyer = new Destroyer(new Integer[]{editor.indexOf(editor.getHighlightedObject())});
				Reviver reviver = new Reviver(destroyer);
				editor.execute(destroyer, reviver, true, "Destroy "+editor.getHighlightedObject(), true, append);
				append = !SEPARATE_UNDO;
			}
			if((paint&PAINT_CREATE) != 0 && cons != null)
			{
				ConstructorInvoker op = new ConstructorInvoker(cons, mpos, true, true);
				Unconstructor inv = new Unconstructor(op);
				editor.execute(op, inv, true, "Create "+cons.declaringType.getSimpleName()+" at "+mpos, true, append);
				append = !SEPARATE_UNDO;
			}
		}
		else if(e.getID() == MouseEvent.MOUSE_RELEASED && e.getButton() == MouseEvent.BUTTON1)
		{
			terminate(false);
		}
		lastMouse.set(mpos);
	}
	@Override
	public void render(EGL<?> egl) 
	{}
	@Override
	public void key(KeyEvent e) 
	{}
	@Override
	public void terminate(boolean cancel) {
		editor.modeFinished();
	}
	@Override
	public boolean shouldUpdateHighlight()
	{
		return true;
	}
}
